package com.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author Yadasu
 * @Description 获取上下文对象的工具类
 * @Date 2020/10/7 11:40
 * @Version 1.0
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext ac;

    /**
     * 获取上下文对象
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }

    /**
     * 获取指定bean对象
     * @param clazz bean对象的clazz
     * @param <T> 泛型参数
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return ac.getBean(clazz);
    }

    /**
     * 获取指定bean对象
     * @param beanName bean的名称
     * @param clazz bean对象的clazz
     * @param <T> 泛型参数
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return ac.getBean(beanName, clazz);
    }
}
